﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ASMS.Excel2DbTool.Utils
{
    /// <summary>
    /// 空运出口目标国家地区货量热力图
    /// </summary>
    public class 空运出口目标国家地区货量热力图
    {
        public static void Run(string filePath, string destFileName)
        {
            DataTable dataTable = Sunboxsoft.Excel.ReadTool.ReadExcel(filePath, true);

            StringBuilder nameBuilder = new StringBuilder();
            StringBuilder valueBuilder = new StringBuilder();
            List<string> names = new List<string>();
            List<decimal> values = new List<decimal>();
            for (int index = 0; index < dataTable.Rows.Count; index++)
            {
                string nameString = Convert.ToString(dataTable.Rows[index][3]).Trim();
                string valueString = Convert.ToString(dataTable.Rows[index][2]).Trim();

                if (string.IsNullOrEmpty(nameString)
                    || string.IsNullOrEmpty(valueString))
                    continue;

                decimal value = 0;
                if (!decimal.TryParse(valueString, out value))
                {
                    continue;
                }


                bool isInsert = false;
                for (int nameIndex = 0; nameIndex < names.Count; nameIndex++)
                {
                    if (string.Equals(names[nameIndex], nameString))
                    {
                        values[nameIndex] += value;
                        isInsert = true;
                    }
                }

                if (!isInsert)
                {
                    names.Add(nameString);
                    values.Add(value);
                }
            }

            for (var index = 0; index < names.Count; index++)
            {
                if (index == 0)
                {
                    nameBuilder.AppendFormat("\"{0}\"", names[index]);
                    valueBuilder.AppendFormat("{0}", values[index]);
                }
                else
                {
                    nameBuilder.AppendFormat(",\"{0}\"", names[index]);
                    valueBuilder.AppendFormat(",{0}", values[index]);
                }
            }
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("{{\"names\":[{0}],\"values\":[{1}]}}", nameBuilder, valueBuilder);

            string destFilePath = string.Format("{0}\\{1}", AppDomain.CurrentDomain.BaseDirectory, destFileName);
            System.IO.File.WriteAllText(destFilePath, builder.ToString());
            Console.WriteLine(string.Format("转换完毕{0},count:{1}", destFilePath, dataTable.Rows.Count));
        }
    }
}